package com.k.ums.config;

import com.k.ums.security.filter.JwtAuthenticationTokenFilter;
import com.k.ums.security.handler.UmsAccessDeniedHandler;
import com.k.ums.security.handler.UmsAuthenticationEntryPoint;
import com.k.ums.security.UmsUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Description:
 * @Author: kt
 * @CreateTime: 2022/1/26
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UmsAuthenticationEntryPoint umsAuthenticationEntryPoint;

    @Autowired
    private UmsAccessDeniedHandler umsAccessDeniedHandler;

    @Autowired
    private UmsUserDetailsService umsUserDetailsService;

    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http
                .csrf().disable() //不使用session,禁用csrf
                .exceptionHandling().authenticationEntryPoint(umsAuthenticationEntryPoint)
                .accessDeniedHandler(umsAccessDeniedHandler)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/login", "/testRedis")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .disable();
    }

    @Bean
    public PasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(umsUserDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    /**
     * 解决AuthenticationManager未注册的问题
     *
     * @return AuthenticationManager
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
